package com.qububu.systemBase.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qububu.systemBase.exceptions.SessionTimeoutException;
import com.qububu.utils.SystemConstants;


/**
 * @author ZCW
 * 
 * @功能 全局过滤器, 用户进入页面的权限管理
 * 
 * @详情 
 * */
@Component
public class SystemInterceptor implements HandlerInterceptor {

	// 许访问的URL地址
	private List<String> allowUrls;

	public List<String> getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(List<String> allowUrls) {
		this.allowUrls = allowUrls;
	}

	/**
	 * @功能 过滤所有请求并做简单处理
	 * @详情
	 * 
	 * @return true 允许访问当前路径, false 不允许访问当前路径
	 * */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		
//		System.out.println("----------------通过过滤器------------------");
		
		String requestUrl = request.getRequestURI();
		
		if (requestUrl.startsWith(request.getContextPath() + "/resource/") ) {
			return true;
		}
        
		//  禁止配置文件中的<mvc:interceptor>中的<list><value>中的路径可以访问
        for(String url : allowUrls) {
        	
            if(requestUrl.endsWith(url)) {
//            	if (logger.isDebugEnabled()) {
//            		logger.debug("This url is marked as allowed:" + requestUrl);
//            	}
                return true;
            }
        }
 
        if(request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME) != null) {  
            return true;
        } else {
//        	logger.info("Session timout when access " + requestUrl);
            throw new SessionTimeoutException("全局过滤器中, Url: " + requestUrl); 
        }
	}

	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
